package com.liyl.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.liyl.entity.*;
import com.liyl.service.IHealthCheckMorningCheckRecService;
import com.liyl.service.IHealthCheckWatchRecService;
import com.liyl.util.ExportUtil;
import com.liyl.vo.ProductionVo;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("file")
public class FileController {

    private static Logger logger = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private IHealthCheckMorningCheckRecService healthCheckMorningCheckRecService;
    @Autowired
    private IHealthCheckWatchRecService healthCheckWatchRecService;

    @GetMapping("download")
    public void download1(HttpServletResponse response) throws IOException {
        List<ProductionVo> productionVoList = new ArrayList<>();
        productionVoList.add(new ProductionVo("1", "232311"));
        productionVoList.add(new ProductionVo("2", "232322"));
        productionVoList.add(new ProductionVo("3", "232333"));
        productionVoList.add(new ProductionVo("4", "232344"));
        productionVoList.add(new ProductionVo("5", "232355"));
        productionVoList.add(new ProductionVo("6", "232366"));

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和 easy excel 没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ProductionVo.class).sheet("模板").doWrite(productionVoList);
    }

    /**
     * 获取晨午检信息
     *
     * @return
     */
    private List<MorningCheckExcelModel> getMorningCheckData(List<HealthCheckMorningCheckRec> checkList) {
        List<MorningCheckExcelModel> data = new ArrayList<>();
        for (HealthCheckMorningCheckRec rec : checkList) {
            MorningCheckExcelModel model = new MorningCheckExcelModel();
            model.setClassName(rec.getClassName());
            model.setName(rec.getChildName());
            model.setCheckTime(rec.getMorningCheckTime());
            model.setTemp(rec.getMorningCheckTemp() + "℃");
            model.setSymptom(rec.getCheckException());
            model.setRemark(rec.getParComp());
            data.add(model);
        }
        return data;
    }
    /**
     * 晨午检的头
     *
     * @param bigTitle
     * @return
     */
    private List<List<String>> getMorningCheckHead(String bigTitle) {
        List<List<String>> head = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<>();
        head0.add(bigTitle);
        head0.add("班级");
        List<String> head1 = new ArrayList<>();
        head1.add(bigTitle);
        head1.add("姓名");
        List<String> head2 = new ArrayList<>();
        head2.add(bigTitle);
        head2.add("晨午检时间");
        List<String> head3 = new ArrayList<>();
        head3.add(bigTitle);
        head3.add("体温");
        List<String> head4 = new ArrayList<>();
        head4.add(bigTitle);
        head4.add("晨午检异常症状");
        List<String> head5 = new ArrayList<>();
        head5.add(bigTitle);
        head5.add("备注");
        head.add(head0);
        head.add(head1);
        head.add(head2);
        head.add(head3);
        head.add(head4);
        head.add(head5);

        return head;
    }

    /**
     * 获取健康观察信息
     *
     * @return
     */
    private List<HealthWatchExcelModel> getHelathWatchData(List<HealthCheckWatchRec> watchRecList) {
        List<HealthWatchExcelModel> data = new ArrayList<>();
        for (HealthCheckWatchRec rec : watchRecList) {
            HealthWatchExcelModel model = new HealthWatchExcelModel();
            model.setCheckTime(rec.getWatchTime());
            model.setClassName(rec.getClassName());
            model.setSymptom(rec.getHealthExceptionInfo());
            model.setOther(rec.getOtherInfo());
            model.setTemp(rec.getWatchTemp() + "℃");
            model.setName(rec.getChildName());
            data.add(model);
        }

        return data;
    }



    /**
     * 健康观察的头
     *
     * @param bigTitle
     * @return
     */
    private List<List<String>> getHealthWatchHead(String bigTitle) {
        List<List<String>> head = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<>();
        head0.add(bigTitle);
        head0.add("班级");
        List<String> head1 = new ArrayList<>();
        head1.add(bigTitle);
        head1.add("姓名");
        List<String> head2 = new ArrayList<>();
        head2.add(bigTitle);
        head2.add("观察时间");
        List<String> head3 = new ArrayList<>();
        head3.add(bigTitle);
        head3.add("体温");
        List<String> head4 = new ArrayList<>();
        head4.add(bigTitle);
        head4.add("健康异常症状");
        List<String> head5 = new ArrayList<>();
        head5.add(bigTitle);
        head5.add("其他情况");
        List<String> head6 = new ArrayList<>();
        head6.add(bigTitle);
        head6.add("备注");
        head.add(head0);
        head.add(head1);
        head.add(head2);
        head.add(head3);
        head.add(head4);
        head.add(head5);
        head.add(head6);
        return head;
    }

    /**
     * 导出晨午检信息
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "exportMorningCheck", method = RequestMethod.GET)
    public void exportMorningCheck(HttpServletResponse response, @RequestBody QueryHealthCheckMorningCheckRec rec) throws Exception {

        if (StringUtils.isEmpty(rec.getKdgId())) {
            return;
        }
        StringBuffer bigTitle = new StringBuffer();
        if (StringUtils.isEmpty(rec.getMorningCheckTime()) || rec.getMorningCheckTime().length() == 0) {
            rec.setMorningCheckTime(DateUtils.format(new Date(), "yyyy-MM-dd"));
            bigTitle.append(DateUtils.format(new Date(), "yyyy年MM月dd日"));
        } else {
            Date date = DateUtils.parseDate(rec.getMorningCheckTime(), "yyyy-MM-dd");
            bigTitle.append(DateUtils.format(date, "yyyy年MM月dd日"));
        }

        List<HealthCheckMorningCheckRec> morningCheckList = healthCheckMorningCheckRecService.getMorningCheckRecInfo(rec);

        if (morningCheckList != null && morningCheckList.size() > 0) {
            bigTitle.append(morningCheckList.get(0).getKdgName());
        }

        bigTitle.append("晨午检详单");

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //String fileName = URLEncoder.encode(bigTitle.toString(), "UTF-8");
        String fileName = URLEncoder.encode("晨检", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + System.currentTimeMillis() + ".xlsx");


        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());

        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);

        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        List<MorningCheckExcelModel> morningCheckExcelModels = getMorningCheckData(morningCheckList);
        List<List<String>> headLists = getMorningCheckHead(bigTitle.toString());
        List<String> stringList = new ArrayList<>();
        stringList.add("className");
        stringList.add("name");
        stringList.add("checkTime");
        stringList.add("temp");
        stringList.add("symptom");
        stringList.add("remark");
        List<List<Object>> objList = ExportUtil.getExportListDatas(morningCheckExcelModels, stringList);
        EasyExcel.write(response.getOutputStream(), MorningCheckExcelModel.class).head(headLists).registerWriteHandler(horizontalCellStyleStrategy).sheet("晨午检").doWrite(objList);
    }


    /**
     * 导出健康观察信息
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "exportHealthWatch", method = RequestMethod.GET)
    public void exportHealthWatch(HttpServletResponse response,@RequestBody QueryHealthCheckWatchRec rec) throws Exception {
        if (StringUtils.isEmpty(rec.getKdgId())) {
            return;
        }
        StringBuffer bigTitle = new StringBuffer();

        if (StringUtils.isEmpty(rec.getWatchTime()) || rec.getWatchTime().length() == 0) {
            rec.setWatchTime(DateUtils.format(new Date(), "yyyy-MM-dd"));
            bigTitle.append(DateUtils.format(new Date(), "yyyy年MM月dd日"));
        } else {
            Date date = DateUtils.parseDate(rec.getWatchTime(), "yyyy-MM-dd");
            bigTitle.append(DateUtils.format(date, "yyyy年MM月dd日"));
        }

        List<HealthCheckWatchRec> healthCheckWatchRecList = healthCheckWatchRecService.getWatchRecInfo(rec);

        if (healthCheckWatchRecList != null && healthCheckWatchRecList.size() > 0) {
            bigTitle.append(healthCheckWatchRecList.get(0).getKdgName());
        }

        bigTitle.append("全日健康观察详单");

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //String fileName = URLEncoder.encode(bigTitle.toString(), "UTF-8");
        String fileName = URLEncoder.encode("健康观察", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + System.currentTimeMillis() + ".xlsx");


        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();

        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);

        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        List<List<String>> lists = getHealthWatchHead(bigTitle.toString());
        EasyExcel.write(response.getOutputStream(), HealthWatchExcelModel.class).head(lists).registerWriteHandler(horizontalCellStyleStrategy).sheet("全日健康观察").doWrite(getHelathWatchData(healthCheckWatchRecList));
    }
}
